package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Create By Administrator on 2021/7/11.
 */
@Service
@Slf4j
public class SoundApiImpl implements SoundApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public String saveSound(Sound sound) {

        try {
            if (!ObjectUtil.isAllNotEmpty(sound.getUserId(), sound.getSoundUrl())) {
                return null;
            }

            //设置id
            sound.setId(ObjectId.get());
            sound.setVid(this.idService.createId(IdType.SOUND));

            //发布时间
            sound.setCreated(System.currentTimeMillis());

            //保存到Mongodb中
            this.mongoTemplate.save(sound);
            return sound.getId().toString();
        } catch (Exception e) {
            log.error("传音失败~sound = " + sound, e);
        }
        return  null;
    }

    @Override
    public Sound receptionsound() {


        Sound sound = null;
        try {
            List<Sound> all = this.mongoTemplate.findAll(Sound.class);

            int r = new Random(all.size()).nextInt();

            sound = all.get(r);

            if (ObjectUtil.isNotEmpty(sound)) {
                //查询到数据
                return sound;
            }
        } catch (Exception e) {
            log.error("获取桃花传音失败了~"+e);
        }
        return sound;
    }

    @Override
    public Integer querySoudById(Long id) {

        String integer = redisTemplate.opsForValue().get("TAOHUA_COUNTS" + id);
        if (integer==null){
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, 1);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.MILLISECOND, 0);
            Long outTime = (cal.getTimeInMillis()-System.currentTimeMillis())/1000;
            redisTemplate.opsForValue().set("TAOHUA_COUNTS" + id,"10",outTime, TimeUnit.SECONDS);
            return 9;
        }else {
            Integer i = Integer.parseInt(integer)-1;

            redisTemplate.opsForValue().set("TAOHUA_COUNTS" + id,i.toString());
            return i;
        }
    }
}
